<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://gettestfire.org/taglibs/" prefix="tf" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>


<html>
<head>
<title>TestFire</title>

<!-- begin common includes -->

<!--aggregate file paths for utilities.js and yahoo-dom-event.js-->
<!--NOTE: Do not use both of these files together; utilities.js includes everything that is
			in yahoo-dom-event.js -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.3.0/build/utilities/utilities.js"></script>
<!--<script type="text/javascript" src="http://yui.yahooapis.com/2.3.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>  -->

<!--aggregate file path for reset-fonts-grids.css-->
<link rel="stylesheet" type="text/css"
      href="http://yui.yahooapis.com/2.3.0/build/reset-fonts-grids/reset-fonts-grids.css">

<!--aggregate file path for YUI Sam Skin CSS for UI controls-->
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.3.0/build/assets/skins/sam/skin.css">

<!--
			  YUI-ext, by Jack Slocum : http://www.jackslocum.com/
			  Docs: http://www.yui-ext.com/deploy/yui-ext/docs/
	  -->
<link rel="stylesheet" type="text/css" href="../../javascript/extjs/resources/css/ext-all.css"/>
<!--<script type="text/javascript" src="/javascript/ext/yui-ext.js"></script>-->

<!--<script type="text/javascript" src="/javascript/ext/ext-core-debug.js"></script>-->
<script type="text/javascript" src="../../javascript/extjs/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../../javascript/extjs/ext-all-debug.js"></script>

<!--<script type="text/javascript" src="/javascript/ext/adapter/yui/ext-yui-adapter.js"></script>-->
<!--<script type="text/javascript" src="/javascript/ext/adapter/yui/yui-utilities.js"></script>-->

<script type="text/javascript" src="../../javascript/webInit.js"></script>


<!--
			  Prototype: http://prototype.conio.net/
			  Good docs: http://www.sergiopereira.com/articles/prototype.js.html
	  -->
<script type="text/javascript" src="../../javascript/prototype/prototype.js"></script>
<link rel="stylesheet" type="text/css" href="../../css/styles.css"/>
<link rel=stylesheet href="../../css/basic.css" type="text/css">

<!-- end common includes -->

<script type="text/javascript">
    /* General JS - global variables and functions. */

    /* Define a page-wide data-store object.*/
    var global = {};

    function formatBoolean(value){
        return value ? 'Yes' : 'No';
    };

    function formatDateTime( value )
    {
        return value.dateFormat('M d, Y H:i:s-T');
    };

    /**
     * Handles the onUpdate listener response for the Queue Datagrid.
     * @param store
     * @param record
     * @param operation
     */
    function onQueueUpdate( store, record, operation )
    {
        if ( operation == Ext.data.Record.EDIT )
        {
            store.commitChanges();
        }
        else if ( operation == Ext.data.Record.COMMIT )
        {
            new Ajax.Request(global.queueSummaryDS.url, {
                method: 'post',
                parameters: {
                    jsonTranslator: "QueueTranslator",
                    jsonActionEl: "QueueAction",
                    jsonActionArgs: "commit,:jsonData",
                    jsonData: Object.toJSON(record.data)
                },
                onSuccess: function( transport )
                {
                    global.queueEditorDS.reload();
                    global.queueSummaryDS.reload();
                }
            });
        }
        else if ( operation == Ext.data.Record.REJECT )
        {
            alert("REJECT in queuetestsets");
        }
        else
        {
            alert("Unknown onUpdate Event in queuetestsets");
        }
    }

    /**
     * Handles the onUpdate listener response for any Testset row; for editing the values of the
     * testset.
     *
     * Sends the data back to the server via an Ajax.Request, if successful causes a refresh of
     * all Testset Grids.
     * @param store
     * @param record
     * @param operation
     */
    function onTestsetRowUpdate( store, record, operation )
    {

        if ( operation == Ext.data.Record.EDIT )
        {
            store.commitChanges();
        }
        else if ( operation == Ext.data.Record.COMMIT )
        {
            var url;
            if ( store == global.availTestsetDS || store == global.enqueuedTestsetDS )
            {
                url = store.url;
            }
            else
            {
                url = global.lastTestsetChangeDS.url;
            }
            new Ajax.Request(url, {
                method: 'post',
                parameters: {
                    jsonTranslator: "TestsetTranslator",
                    jsonActionEl: "TestsetAction",
                    jsonActionArgs: "commit,:jsonData",
                    jsonData: Object.toJSON(record.data)
                },
            /* JSON will only be set if an X-JSON header is present on the response.*/
                onSuccess: function( transport, json )
                {
                    if ( store == global.availTestsetDS )
                    {
                        global.availTestsetDS.reload();
                    }
                    else if ( store == global.enqueuedTestsetDS )
                    {
                        global.enqueuedTestsetDS.reload();
                    }
                    else
                    {
                        global.lastTestsetChangeDS.reload();
                    }

                },
                onFailure: function( transport )
                {
                    alert('Error updating: Status code ' + transport.status + ' returned by server.');
                }
            });

        }
    }



    /**
     * Handles the onUpdate listener response for any Testset row; for editing the values of the
     * testset.
     *
     * Sends the data back to the server via an Ajax.Request, if successful causes a refresh of
     * all Testset Grids.
     * @param store
     * @param record
     * @param operation
     */
    function onTestRowUpdate( store, record, operation )
    {
        if ( operation == Ext.data.Record.EDIT )
        {
            store.commitChanges();
        }
        else if ( operation == Ext.data.Record.COMMIT )
        {
            var url = store.url;

            new Ajax.Request(url, {
                method: 'post',
                parameters: {
                    jsonTranslator: "TestTranslator",
                    jsonActionEl: "TestAction",
                    jsonActionArgs: "commit,:jsonData",
                    jsonData: Object.toJSON(record.data)
                },
            /* JSON will only be set if an X-JSON header is present on the response.*/
                onSuccess: function( transport, json )
                {
                    global.testDS.reload();
                    global.testGrid.autoSize();
                },
                onFailure: function( transport )
                {
                    alert('Error updating: Status code ' + transport.status + ' returned by server.');
                }
            });

        }
    }

    /**
     * onUpdate Listener for the Agent grid rows.
     * When a row is modified the values will be sent to the server. On a successful
     * update, all Agent Grids will be refreshed. 
     *
     * @param store
     * @param record
     * @param operation
     */
    function onAgentUpdate( store, record, operation )
    {
        if ( operation == Ext.data.Record.EDIT )
        {
            store.commitChanges();
        }
        else if ( operation == Ext.data.Record.COMMIT )
        {
            var url;
            if ( store == global.availAgentDS || store == global.inUseAgentDS )
            {
                url = store.url;
            }
            else
            {
                url = global.lastAgentChangeDS.url;
            }
            new Ajax.Request(url, {
                method: 'post',
                parameters: {
                    jsonTranslator: "AgentTranslator",
                    jsonActionEl: "AgentAction",
                    jsonActionArgs: "commit,:jsonData",
                    jsonData: Object.toJSON(record.data)
                },
                onSuccess: function( transport )
                {
                    if ( store == global.availAgentDS )
                    {
                        global.availAgentDS.reload();
                    }
                    else if ( store == global.inUseAgentDS )
                    {
                        global.inUseAgentDS.reload();
                    }
                    else
                    {
                        global.lastAgentChangeDS.reload();
                    }

                }
            });
        }

    }

    /**
     * All grids in the page must add this method as an onLoad listener.
     *
     * Updates the global information regarding who is selected in which grids;
     * the Editor panel requires this information.
     * @param store
     * @param records
     * @param options
     */
    function onLoad( store, records, options )
    {
        if ( store == global.queueSummaryDS )
        {
            if ( global.selectedQueueRow || global.selectedQueueRow == 0 )
                global.queueGrid.getSelectionModel().selectRow(global.selectedQueueRow);
            else
                global.queueGrid.getSelectionModel().selectFirstRow();
            global.selectedQueueRow = null;
            global.lastAgentChangeDS= null;
        }
        else if ( global.lastTestsetChangeDS != null && (global.selectedTestsetRow || global.selectedTestsetRow == 0) )
        {
            if ( store == global.availTestsetDS )
            {
                global.availTestsetGrid.getSelectionModel().selectRow(global.selectedTestsetRow);
            }
            else if ( store == global.enqueuedTestsetDS )
            {
                global.enqueuedTestsetGrid.getSelectionModel().selectRow(global.selectedTestsetRow);
            }
            global.selectedTestsetRow = null;
            global.lastTestsetChangeDS = null;
        }
        else if ( global.lastAgentChangeDS != null && (global.selectedAgentRow || global.selectedAgentRow == 0) )
        {
            if ( store == global.availAgentDS )
            {
                global.availAgentGrid.getSelectionModel().selectRow(global.selectedAgentRow);
            }
            else if ( store == global.inUseAgentDS )
            {
                global.inUseAgentGrid.getSelectionModel().selectRow(global.selectedAgentRow);
            }
            global.selectedAgentRow = null;
            global.lastAgentChangeDS = null;
        }
    }


</script>

<script type="text/javascript">
    /* Queue Grid. */
    global.selectedQueueId = null;
    global.selectedQueueRow = null;
    global.queueSummaryDS = null;
    global.queueEditorDS = null;
    global.queueGrid = null;
    Ext.onReady(function()
    {
        Ext.QuickTips.init();

        var allCols = [{
            header: "ID",
            dataIndex: 'id',
            width: 30
        },{
            header: "Name",
            width: 150,
            dataIndex: 'name',
            editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false}))
        },{
            header: "Schedule String (Cron format)",
            dataIndex: 'cronTask',
            width: 200,
            editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false}))
        },{
            header: "User",
            width: 100,
            dataIndex: 'userName'
        },{
            header: "Use Any Available Agent",
            dataIndex: "useAnyAvailableAgent",
            width: 100,
            renderer: formatBoolean,
            editor: new Ext.grid.GridEditor(new Ext.form.Checkbox())
        },{
            header: "Description",
            dataIndex: 'description',
            width: 400,
            editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: true}))
        }];
        var allColModel = new Ext.grid.DefaultColumnModel(allCols);
        var queueEditorModel = new Ext.grid.RowSelectionModel({singleSelect: true});

        var colModel = new Ext.grid.DefaultColumnModel(allCols.slice(0, 3));
        colModel.defaultSortable = true;
        var fields = [
        {name: 'id', type: 'int'},
        {name: 'name', type: 'string'},
        {name: 'cronTask', type: 'string'},
        {name: 'userName', type: 'string'},
        {name: 'useAnyAvailableAgent', type: 'boolean'},
        {name: 'description', type: 'string'},
            ];

        var queueType = Ext.data.Record.create(fields);
         /* Weird stuff like this is possible when we define the Record Type as above. */
        //			var q = new queueType({
        //					description:"Run every weekday at 8pm (20:00 hours).",
        //					name:"default_queue",
        //					cronTask :"* 20 * * 1,2,3,4,5",
        //					id:1
        //			});
        // global.queueEditorDS.load();
        // global.queueEditorDS.add(q);
        /* But we don't do that. It would be useful when we turn most of this code into widgets/tags. */

        /**
         * The Editor panel doesn't require a full read from the server; we transfer
         * the data from the summary panel, which read in full from the server, to a
         * MemoryProxy backed data store.
         */
        global.queueEditorDS = new Ext.data.Store({
            proxy: new Ext.data.MemoryProxy({
                result: [ ]
            }),
            reader: new Ext.data.JsonReader(
            {
                root: 'result',
                id: 'id'
            }, queueType)
        });

        global.queueEditorDS.load();
        global.queueEditorDS.on('update', onQueueUpdate);
        var queueEditorGrid = new Ext.grid.EditorGrid('queue-editor-grid', {
            ds: global.queueEditorDS,
            cm: allColModel,
            selModel: queueEditorModel,
            autoHeight: true
        });
			// to use double click to edit:
        queueEditorGrid.getSelectionModel().clicksToActivateCell = 2;
        queueEditorGrid.render();

        global.queueSummaryDS = new Ext.data.JsonStore({
            url: '../json/jsonRequest.jsf',
            baseParams: {
                jsonActionEl: "CreateJsonStoreAction",
                jsonActionArgs: ":rows,:jsonTranslator,:fields",
                jsonTranslator: "QueueTranslator",
                rows: "queueBean.queues",
                fields: fields.toJSON() },
            root: 'result',
            fields: fields
        });

        // Add the Update Listener; this listens for changes to cell/field data (e.g. description or name is modified).
        global.queueSummaryDS.on('update', onQueueUpdate);
        global.queueSummaryDS.on('load', onLoad);
        var queueSelModel = new Ext.grid.RowSelectionModel({singleSelect: true});
        var selChangeListener = function( selModel )
        {
            if ( selModel.selections.length > 0 )
            {
                var data = selModel.selections.items[0].data;
                global.selectedQueueId = data.id;
                global.selectedQueueRow = selModel.lastActive;
                /* change the queue ID and load the test sets. */
                global.enqueuedTestsetDS.baseParams.queueId = data.id;
                global.availTestsetDS.baseParams.queueId = data.id;
                global.enqueuedTestsetDS.reload();
                global.availTestsetDS.reload();

                /* change the queue ID and load the test sets. */
                global.inUseAgentDS.baseParams.queueId = data.id;
                global.availAgentDS.baseParams.queueId = data.id;
                global.inUseAgentDS.reload();
                global.availAgentDS.reload();

                global.queueEditorDS.removeAll();
                global.queueEditorDS.add(selModel.selections.items);
            }
        }
        queueSelModel.on('selectionchange', selChangeListener);
        global.queueGrid = new Ext.grid.EditorGrid('queue-summary-grid', {
            ds: global.queueSummaryDS,
            cm: colModel,
            selModel: queueSelModel,
            autoHeight: true
        });

		    // to use double click to edit:
        global.queueGrid.getSelectionModel().clicksToActivateCell = 2;
        global.queueGrid.render();

        var gridHead = global.queueGrid.getView().getHeaderPanel(true);

        var addQueueBtn = {
            text: 'Add Queue',
            handler : function()
            {
                new Ajax.Request(global.queueSummaryDS.url, {
                    method: 'post',
                    parameters: {
                        jsonTranslator: "QueueTranslator",
                        jsonActionEl: "QueueAction",
                        jsonActionArgs: "new"
                    },
                    onSuccess: function( transport )
                    {
                        global.queueSummaryDS.reload();
                    }
                });
            }
        };

        var runQueueNowButton = {
            text: 'Run Queue Now',
            handler : function()
            {
                new Ajax.Request(global.queueSummaryDS.url, {
                    method: 'post',
                    parameters: {
                        jsonTranslator: "QueueTranslator",
                        jsonActionEl: "RunQueueNowAction",
                        jsonActionArgs: global.selectedQueueId
                    },
                    onSuccess: function( transport )
                    {

                    }
                });
            }
        };

        var tb = new Ext.Toolbar(gridHead, [addQueueBtn, runQueueNowButton]);

        global.queueSummaryDS.load();
    });


</script>


<script type="text/javascript">
    /*
                   Create both Testset Grids.
                   This is WAY to big, all of the grid code needs to be refactored into something reusable. Use tags, beans,
                        whatever.
           */
    global.availTestsetDS = null;
    global.availTestsetGrid = null;
    global.enqueuedTestsetDS = null;
    global.enqueuedTestsetGrid = null;

    global.testsetAllInfoDS = null;
    global.lastTestsetChangeDS = null;
    global.selectedTestsetRow = null;
    global.selectedTestsetId = null;
    Ext.onReady(function()
    {
        Ext.QuickTips.init();



        var cols = [{
            header: "ID",
            dataIndex: 'id',
            width: 30
        },{
            header: "Name",
            dataIndex: 'name',
            width: 150,
            editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false}))
        },{
            header: "Description",
            dataIndex: 'description',
            width: 200,
            editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false}))
        },{
            header: "Created",
            width: 200,
            dataIndex: 'created',
            renderer: formatDateTime


        },{
            header: "Last Verified",
            dataIndex: 'lastverified',
            width: 200,
            renderer: formatDateTime,
            editor: new Ext.grid.GridEditor(new Ext.form.DateField({format: 'm/d/y H:i:s-T'}))
        },{
            header: "For Bug",
            dataIndex: 'forbug',
            width: 120,
            editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: true}))
        }];
        var colModel = new Ext.grid.DefaultColumnModel(cols.slice(0, 3));
        colModel.defaultSortable = true;

        var fields = [
        {name: 'id', type: 'int'},
        {name: 'name', type: 'string'},
        {name: 'created', type: 'date'},
        {name: 'lastverified', type: 'date'},
        {name: 'forbug', type: 'string'},
        {name: 'description', type: 'string'}
            ];

        global.enqueuedTestsetDS = new Ext.data.JsonStore({
            url: '../json/jsonRequest.jsf',
            baseParams: {
                jsonActionEl: "CreateJsonStoreAction",
                jsonActionArgs: ":rows,:jsonTranslator,:fields,:queueId",
                queueId: global.selectedQueueId,
                rows: "queueBean.testsets",
                jsonTranslator: "TestsetTranslator",
                fields: fields.toJSON() },
            root: 'result',
            fields: fields
        });

        global.availTestsetDS = new Ext.data.JsonStore({
            url: '../json/jsonRequest.jsf',
            baseParams: {
                jsonActionEl: "CreateJsonStoreAction",
                jsonActionArgs: ":rows,:jsonTranslator,:fields,:queueId",
                queueId: global.selectedQueueId,
                rows: "queueBean.availableTestsets",
                jsonTranslator: "TestsetTranslator",
                fields: fields.toJSON() },
            root: 'result',
            fields: fields
        });

        global.enqueuedTestsetDS.on('update', onTestsetRowUpdate);
        global.enqueuedTestsetDS.on('load', onLoad);
        global.availTestsetDS.on('update', onTestsetRowUpdate);
        global.availTestsetDS.on('load', onLoad);
        var enqueuedSM = new Ext.grid.RowSelectionModel({singleSelect: false});
        var availSM = new Ext.grid.RowSelectionModel({singleSelect: false});

        /*----------------   Info View Grid ------------*/
        var testsetType = Ext.data.Record.create(fields);
        var allColModel = new Ext.grid.DefaultColumnModel(cols);
        allColModel.defaultSortable = true;
        global.testsetAllInfoDS = new Ext.data.Store({
            proxy: new Ext.data.MemoryProxy({
                result: [ ]
            }),
            reader: new Ext.data.JsonReader(
            {
                root: 'result',
                id: 'id'
            }, testsetType)
        });
        global.testsetAllInfoDS.load();
        global.testsetAllInfoDS.on('update', onTestsetRowUpdate);
        var enqueuedAllColSelModel = new Ext.grid.RowSelectionModel({singleSelect: true});
        var enqueuedAllColGrid = new Ext.grid.EditorGrid('testset-info-grid', {
            ds: global.testsetAllInfoDS,
            cm: allColModel,
            selModel: enqueuedAllColSelModel,
            autoHeight: true
        });
			// to use double click to edit:
        enqueuedAllColGrid.getSelectionModel().clicksToActivateCell = 2;
        enqueuedAllColGrid.render();

        /*----------------   Limited View Grid ------------*/

        global.enqueuedTestsetGrid = new Ext.grid.EditorGrid('queuetestsets-grid', {
            ds: global.enqueuedTestsetDS,
            cm: colModel,
            enableDragDrop: true,
            selModel: enqueuedSM,
            autoHeight: true

        });

        global.availTestsetGrid = new Ext.grid.EditorGrid('testset-grid', {
            ds: global.availTestsetDS,
            cm: colModel,
            enableDragDrop: true,
            selModel: availSM,
            autoHeight: true

        });

        new Ext.dd.DropTarget(global.enqueuedTestsetGrid.container, {
            ddGroup : 'GridDD',
            notifyDrop : function( dd, e, data )
            {
                var rows = data.selections;
                for ( var i = 0; i < rows.length; i++ )
                {
                    data.grid.dataSource.remove(rows[i]);
                    global.enqueuedTestsetGrid.dataSource.add(rows[i]);
                    new Ajax.Request(global.enqueuedTestsetGrid.dataSource.url, {
                        method: 'post',
                        parameters: {
                            jsonTranslator: "TestsetTranslator",
                            jsonActionEl: "QueueAction",
                            jsonActionArgs: "add,:jsonData,:queueId",
                            queueId: global.selectedQueueId,
                            jsonData: Object.toJSON(rows[i].data)
                        },
                        onSuccess: function( transport )
                        {
                            global.enqueuedTestsetGrid.dataSource.reload();
                            data.grid.dataSource.reload();
                        }
                    });

                }
            }
        });

        var enqueuedSelChangeListener = function( selModel )
        {
            if ( selModel.selections.length > 0 )
            {
                var data = selModel.selections.items[0].data;
                global.selectedTestsetId = data.id;
                global.selectedTestsetRow = selModel.lastActive;
                global.testsetAllInfoDS.removeAll();
                global.testsetAllInfoDS.add(selModel.selections.items);
                global.lastTestsetChangeDS = global.enqueuedTestsetDS;

                global.availTestsetGrid.getSelectionModel().clearSelections();

                /* change the testset ID and load the tests. */
                global.testDS.baseParams.testsetId = data.id;
                global.testDS.reload();
                 /* change the testset ID and load the testset Results. */
                global.testsetResultDS.baseParams.testsetId = data.id;
                global.testsetResultDS.reload();
            }
        }

        var availSelChangeListener = function( selModel )
        {
            if ( selModel.selections.length > 0 )
            {
                var data = selModel.selections.items[0].data;
                global.selectedTestsetId = data.id;
                global.selectedTestsetRow = selModel.lastActive;
                global.testsetAllInfoDS.removeAll();
                global.testsetAllInfoDS.add(selModel.selections.items);
                global.lastTestsetChangeDS = global.availTestsetDS;

                global.enqueuedTestsetGrid.getSelectionModel().clearSelections();

                /* change the testset ID and load the tests. */
                global.testDS.baseParams.testsetId = data.id;
                global.testDS.reload();
                /* change the testset ID and load the testset Results. */
                global.testsetResultDS.baseParams.testsetId = data.id;
                global.testsetResultDS.reload();
            }
        }

        enqueuedSM.on('selectionchange', enqueuedSelChangeListener);
        availSM.on('selectionchange', availSelChangeListener);

        enqueuedSM.clicksToActivateCell = 2;
        availSM.clicksToActivateCell = 2;
        global.enqueuedTestsetGrid.render();
        global.availTestsetGrid.render();


        var gridHead = global.enqueuedTestsetGrid.getView().getHeaderPanel(true);

        var removeEnqueuedTestsetButton = {
            text: 'Remove',
            handler : function()
            {
                new Ajax.Request(global.queueSummaryDS.url, {
                    method: 'post',
                    parameters: {
                        jsonTranslator: "TestsetTranslator",
                        jsonActionEl: "QueueAction",
                        jsonActionArgs: "remove,:testsetId,:queueId",
                        testsetId: global.selectedTestsetId,
                        queueId: global.selectedQueueId
                    },
                    onSuccess: function( transport )
                    {
                        global.availTestsetDS.reload();
                        global.enqueuedTestsetDS.reload();
                        global.testsetAllInfoDS.reload();
                    }
                });
            }
        };

        var tb = new Ext.Toolbar(gridHead, [removeEnqueuedTestsetButton]);
        /* Don't load these datasources, they will be loaded by the onload event of the queueGrid. */


    });


</script>


<script type="text/javascript">
    /*
                   Create both Agent grids.
                   This is WAY to big, all of the grid code needs to be refactored into something reusable. Use tags, beans,
                        whatever.
           */
    global.availAgentDS = null;
    global.availAgentGrid = null;
    global.inUseAgentDS = null;
    global.inUseAgentGrid = null;

    global.agentAllInfoDS = null;
    global.lastAgentChangeDS = null;
    global.selectedAgentRow = null;
    global.selectedAgentId = null;
    Ext.onReady(function()
    {
        Ext.QuickTips.init();
        function formatBoolean( value )
        {
            return value ? 'Yes' : 'No';
        }
        ;

        function formatDateTime( value )
        {
            return value.dateFormat('M d, Y H:i:s-T');
        }
        ;

        var cols = [{
            header: "ID",
            dataIndex: 'id',
            width: 30
        },{
            header: "Name",
            dataIndex: 'name',
            width: 150,
            editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false}))
        },{
            header: "Description",
            dataIndex: 'description',
            width: 200,
            editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false}))
        },{
            header: "Host",
            dataIndex: 'host',
            width: 200,
            editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false}))
        },{
            header: "User",
            dataIndex: 'userName',
            width: 100
        },{
            header: "Public",
            dataIndex: 'allowNonUserTests',
            width: 120,
            renderer: formatBoolean,
            editor: new Ext.grid.GridEditor(new Ext.form.Checkbox())
        },{
            header: "Has Testset",
            dataIndex: 'hastestset',
            width: 100
        }
            ];
        var colModel = new Ext.grid.DefaultColumnModel(cols.slice(0, 3));
        colModel.defaultSortable = true;

        var fields = [
        {name: 'id', type: 'int'},
        {name: 'name', type: 'string'},
        {name: 'description', type: 'string'},
        {name: 'host', type: 'string'},
        {name: 'userName', type: 'string'},
        {name: 'allowNonUserTests', type: 'boolean'},
        {name: 'hastestset', type: 'string'},
            ];

        global.inUseAgentDS = new Ext.data.JsonStore({
            url: '../json/jsonRequest.jsf',
            baseParams: {
                jsonActionEl: "CreateJsonStoreAction",
                jsonActionArgs: ":rows,:jsonTranslator,:fields,:queueId",
                queueId: global.selectedQueueId,
                rows: "queueBean.agents",
                jsonTranslator: "AgentTranslator",
                fields: fields.toJSON() },
            root: 'result',
            fields: fields
        });

        global.availAgentDS = new Ext.data.JsonStore({
            url: '../json/jsonRequest.jsf',
            baseParams: {
                jsonActionEl: "CreateJsonStoreAction",
                jsonActionArgs: ":rows,:jsonTranslator,:fields,:queueId",
                queueId: global.selectedQueueId,
                rows: "queueBean.availableAgents",
                jsonTranslator: "AgentTranslator",
                fields: fields.toJSON() },
            root: 'result',
            fields: fields
        });

        global.inUseAgentDS.on('update', onAgentUpdate);
        global.inUseAgentDS.on('load', onLoad);
        global.availAgentDS.on('update', onAgentUpdate);
        global.availAgentDS.on('load', onLoad);
        var enqueuedSM = new Ext.grid.RowSelectionModel({singleSelect: false});
        var availSM = new Ext.grid.RowSelectionModel({singleSelect: false});

        /*----------------   Info View Grid ------------*/
        var testsetType = Ext.data.Record.create(fields);
        var allColModel = new Ext.grid.DefaultColumnModel(cols);
        allColModel.defaultSortable = true;
        global.agentAllInfoDS = new Ext.data.Store({
            proxy: new Ext.data.MemoryProxy({
                result: [ ]
            }),
            reader: new Ext.data.JsonReader(
            {
                root: 'result',
                id: 'id'
            }, testsetType)
        });
        global.agentAllInfoDS.load();
        global.agentAllInfoDS.on('update', onAgentUpdate);
        var enqueuedAllColSelModel = new Ext.grid.RowSelectionModel({singleSelect: true});
        var enqueuedAllColGrid = new Ext.grid.EditorGrid('agent-info-grid', {
            ds: global.agentAllInfoDS,
            cm: allColModel,
            selModel: enqueuedAllColSelModel,
            autoHeight: true
        });
			// to use double click to edit:
        enqueuedAllColGrid.getSelectionModel().clicksToActivateCell = 2;
        enqueuedAllColGrid.render();

        /*----------------   Limited View Grid ------------*/

        global.inUseAgentGrid = new Ext.grid.EditorGrid('inUseAgent-grid', {
            ds: global.inUseAgentDS,
            ddGroup : 'agentGridDD',
            cm: colModel,
            enableDragDrop: true,
            selModel: enqueuedSM,
            autoHeight: true

        });

        global.availAgentGrid = new Ext.grid.EditorGrid('agent-grid', {
            ds: global.availAgentDS,
            ddGroup : 'agentGridDD',
            cm: colModel,
            enableDragDrop: true,
            selModel: availSM,
            autoHeight: true

        });

        new Ext.dd.DropTarget(global.inUseAgentGrid.container, {
            ddGroup : 'agentGridDD',
            notifyDrop : function( dd, e, data )
            {
                var rows = data.selections;
                for ( var i = 0; i < rows.length; i++ )
                {
                    data.grid.dataSource.remove(rows[i]);
                    global.inUseAgentGrid.dataSource.add(rows[i]);
                    new Ajax.Request(global.inUseAgentGrid.dataSource.url, {
                        method: 'post',
                        parameters: {
                            jsonTranslator: "AgentTranslator",
                            jsonActionEl: "QueueAction",
                            jsonActionArgs: "addAgent,:jsonData,:queueId",
                            queueId: global.selectedQueueId,
                            jsonData: Object.toJSON(rows[i].data)
                        },
                        onSuccess: function( transport )
                        {
                            global.inUseAgentGrid.dataSource.reload();
                            data.grid.dataSource.reload();
                        }
                    });

                }
            }
        });

        new Ext.dd.DropTarget(global.availAgentGrid.container, {
            ddGroup : 'agentGridDD',
            notifyDrop : function( dd, e, data )
            {
                var rows = data.selections;
                for ( var i = 0; i < rows.length; i++ )
                {
                    // delete the row.
                }
            }
        });

        var enqueuedSelChangeListener = function( selModel )
        {
            if ( selModel.selections.length > 0 )
            {
                var data = selModel.selections.items[0].data;
                global.selectedAgentId = data.id;
                global.selectedAgentRow = selModel.lastActive;
                global.agentAllInfoDS.removeAll();
                global.agentAllInfoDS.add(selModel.selections.items);
                global.lastAgentChangeDS = global.inUseAgentDS;

                global.availAgentGrid.getSelectionModel().clearSelections();
            }
        }

        var availSelChangeListener = function( selModel )
        {
            if ( selModel.selections.length > 0 )
            {
                var data = selModel.selections.items[0].data;
                global.selectedAgentId = data.id;
                global.selectedAgentRow = selModel.lastActive;
                global.agentAllInfoDS.removeAll();
                global.agentAllInfoDS.add(selModel.selections.items);
                global.lastAgentChangeDS = global.availAgentDS;

                global.inUseAgentGrid.getSelectionModel().clearSelections();
            }
        }

        enqueuedSM.on('selectionchange', enqueuedSelChangeListener);
        availSM.on('selectionchange', availSelChangeListener);

        enqueuedSM.clicksToActivateCell = 2;
        availSM.clicksToActivateCell = 2;
        global.inUseAgentGrid.render();
        global.availAgentGrid.render();

        var gridHead = global.inUseAgentGrid.getView().getHeaderPanel(true);

        var removeInUseAgentButton = {
            text: 'Remove',
            handler : function()
            {
                new Ajax.Request(global.queueSummaryDS.url, {
                    method: 'post',
                    parameters: {
                        jsonTranslator: "AgentTranslator",
                        jsonActionEl: "QueueAction",
                        jsonActionArgs: "removeAgent,:agentId,:queueId",
                        agentId: global.selectedAgentId,
                        queueId: global.selectedQueueId
                    },
                    onSuccess: function( transport )
                    {
                        global.lastAgentChangeDS.reload();
                        global.inUseAgentDS.reload();
                        global.availAgentDS.reload();
                    }
                });
            }
        };

        var releaseForReuse = {
                    text: 'Clear HasTest',
                    handler : function()
                    {
                        new Ajax.Request(global.queueSummaryDS.url, {
                            method: 'post',
                            parameters: {
                                jsonTranslator: "AgentTranslator",
                                jsonActionEl: "AgentAction",
                                jsonActionArgs: "clear_testset,:agentId",
                                agentId: global.selectedAgentId

                            },
                            onSuccess: function( transport )
                            {
                                global.lastAgentChangeDS.reload();
                        global.inUseAgentDS.reload();
                        global.availAgentDS.reload();
                            }
                        });
                    }
                };


        var tb = new Ext.Toolbar(gridHead, [removeInUseAgentButton, releaseForReuse]);
        /* Don't load these, they will be loaded by the onload event of the queueGrid. */
        //			global.inUseAgentDS.load();
        //			global.availAgentDS.load();

    });


</script>


<script type="text/javascript">
    /* Tests Grid. */
    global.selectedTestId = null;
    global.selectedTestRow = null;
    global.testDS = null;
    global.testGrid = null;
    Ext.onReady(function()
    {
        Ext.QuickTips.init();

        var allCols = [{
            header: "ID",
            dataIndex: 'id',
            width: 30
        },{
            header: "Name",
            width: 150,
            dataIndex: 'name',
            editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false}))
        },{
            header: "For Bug",
            dataIndex: 'forbug',
            width: 80,
            editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false}))
        },{
            header: "Created",
            width: 150,
            dataIndex: 'created',
            renderer: formatDateTime
        },{
            header: "Description",
            dataIndex: 'description',
            width: 200,
            editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: true}))
        }];
        var testModel = new Ext.grid.DefaultColumnModel(allCols);


        testModel.defaultSortable = true;
        var fields = [
        {name: 'id', type: 'int'},
        {name: 'name', type: 'string'},
        {name: 'forbug', type: 'string'},
        {name: 'created', type: 'date'},
        {name: 'description', type: 'string'},
            ];

//        var testType = Ext.data.Record.create(fields);

        global.testDS = new Ext.data.JsonStore({
            url: '../json/jsonRequest.jsf',
            baseParams: {
                jsonActionEl: "CreateJsonStoreAction",
                jsonActionArgs: ":rows,:jsonTranslator,:fields,:testsetId",
                testsetId: global.selectedTestsetId,
                rows: "TestsetBean.tests",
                jsonTranslator: "TestTranslator",
                fields: fields.toJSON() },
            root: 'result',
            fields: fields
        });

        // Add the Update Listener; this listens for changes to cell/field data (e.g. description or name is modified).
        global.testDS.on('update', onTestRowUpdate);
        var testSelectionModel = new Ext.grid.RowSelectionModel({singleSelect: true});
        var testSelectionChangedListener = function( selModel )
        {
            if ( selModel.selections.length > 0 )
            {
                var data = selModel.selections.items[0].data;
                global.selectedTestId = data.id;
                global.selectedTestRow = selModel.lastActive;
            }
        }
        testSelectionModel.on('selectionchange', testSelectionChangedListener);
        global.testGrid = new Ext.grid.EditorGrid('test-grid', {
            ds: global.testDS,
            cm: testModel,
            selModel: testSelectionModel,
            autoHeight: true            
        });

		    // to use double click to edit:
        global.testGrid.getSelectionModel().clicksToActivateCell = 2;
        global.testGrid.render();

    });


</script>


<script type="text/javascript">
    /* Tests Grid. */
    global.selectedTestsetResultId = null;
    global.selectedTestsetResultRow = null;
    global.TestsetResultDS = null;

    global.testGrid = null;
    Ext.onReady(function()
    {
        Ext.QuickTips.init();

        var allCols = [{
            header: "ID",
            dataIndex: 'id',
            width: 30
        },{
            header: "Last Run",
            width: 150,
            dataIndex: 'started',
            renderer: formatDateTime
        },{
            header: "Failure Count",
            dataIndex: 'failureCount',
            width: 100
        },{
            header: "Run Time",
            width: 100,
            dataIndex: 'runTime'
        },{
            header: "Error Message",
            dataIndex: 'errorMessage',
            width: 200
        }];
        var testsetResultModel = new Ext.grid.DefaultColumnModel(allCols);


        testsetResultModel.defaultSortable = true;
        var fields = [
        {name: 'id', type: 'int'},
        {name: 'started', type: 'date'},
        {name: 'failureCount', type: 'int'},
        {name: 'runTime', type: 'int'},
        {name: 'errorMessage', type: 'string'},
            ];

//        var testType = Ext.data.Record.create(fields);

        global.testsetResultDS = new Ext.data.JsonStore({
            url: '../json/jsonRequest.jsf',
            baseParams: {
                jsonActionEl: "CreateJsonStoreAction",
                jsonActionArgs: ":rows,:jsonTranslator,:fields,:testsetId",
                testsetId: global.selectedTestsetId,
                rows: "TestsetResultBean.testsetResults",
                jsonTranslator: "TestsetResultTranslator",
                fields: fields.toJSON() },
            root: 'result',
            fields: fields
        });

        // Not editable, no update listener needed.

        var testsetResultSelectionModel = new Ext.grid.RowSelectionModel({singleSelect: true});


        global.testsetResultGrid = new Ext.grid.EditorGrid('testsetResult-grid', {
            ds: global.testsetResultDS,
            cm: testsetResultModel,
            selModel: testsetResultSelectionModel,
            autoHeight: true
        });

		    // to use double click to edit:
        global.testsetResultGrid.getSelectionModel().clicksToActivateCell = 2;
        global.testsetResultGrid.render();

//        var gridHead = global.testGrid.getView().getHeaderPanel(true);
//
//        var addQueueBtn = {
//            text: 'Add Queue',
//            handler : function()
//            {
//                new Ajax.Request(global.queueSummaryDS.url, {
//                    method: 'post',
//                    parameters: {
//                        jsonTranslator: "QueueTranslator",
//                        jsonActionEl: "QueueAction",
//                        jsonActionArgs: "new"
//                    },
//                    onSuccess: function( transport )
//                    {
//                        global.queueSummaryDS.reload();
//                    }
//                });
//            }
//        };
//
//
//        var tb = new Ext.Toolbar(gridHead, [addQueueBtn, runQueueNowButton]);
// loading will be done via the Testset selection changed event.

    });


</script>


<script type="text/javascript">
    /* Layout JS */
    TestFireMain = function()
    {
        var layout;
        var eastLayout;
        return {
            init : function()
            {
                eastLayout = new Ext.BorderLayout(document.getElementById('east'), {
                    hideOnLayout: true,
                    center: {
                        split:true,
                        initialSize: 200,
                        maxSize: 1200,
                        collapsible: true,
                        titlebar: true,
                        autoScroll:true
                    },
                    north: {
                        split:true,
                        initialSize: 200,
                        maxSize: 1200,
                        collapsible: true,
                        titlebar: true,
                        autoScroll:true
                    },

                    south: {
                        split:true,
                        initialSize: 200,
                        minSize: 100,
                        maxSize: 1200,
                        titlebar: true,
                        collapsible: true
                    }

                });

                eastLayout.add('north', new Ext.ContentPanel('eastNorth', {title: 'Queues', closable:false}));
                eastLayout.add('center', new Ext.ContentPanel('eastCenter', {title: 'Enqueued Testsets', closable: false}));
                eastLayout.add('south', new Ext.ContentPanel('eastSouth', {title: 'Agents to Utilize', closable: false}));

                westLayout = new Ext.BorderLayout(document.getElementById('west'), {
                    hideOnLayout: true,
                    north: {
                        split:true,
                        initialSize: 500,
                        maxSize: 1200,
                        collapsible: true,
                        titlebar: true,
                        autoScroll:true
                    },
                    center: {
                        split:false,
                        initialSize: 0,
                        maxSize: 1200,
                        collapsible: true,
                        titlebar: false,
                        autoScroll:false
                    },
                    south: {
                        split:true,
                        initialSize: 200,
                        minSize: 100,
                        maxSize: 1200,
                        titlebar: true,
                        collapsible: true
                    }

                });

                westLayout.add('north', new Ext.ContentPanel('westNorth', {title: 'Available Testsets', closable:false}));
                westLayout.add('center', new Ext.ContentPanel('westCenter', {closable: false}));
                westLayout.add('south', new Ext.ContentPanel('westSouth', {title: 'Available Agents', closable: false}));

                centerLayout = new Ext.BorderLayout(document.getElementById('center'), {
                    hideOnLayout: true,
                    north:  {
                        split: true,
                        minSize: 100,
                        initialSize: 300,
                        maxSize: 5000,
                        collapsible: true,
                        titlebar: true,
                        autoScroll:true
                    },
                    center: {
                        split: false,
                        minSize: 1,
                        initialSize: 1,
                        maxSize: 1,
                        collapsible: false,
                        titlebar: false,
                        autoScroll:false
                    },
                    south: {
                        split: true,
                        minSize: 100,
                        initialSize: 300,
                        maxSize: 5000,
                        collapsible: true,
                        titlebar: true,
                        autoScroll:true

                    }                    

                });

                
                centerLayout.add('north', new Ext.ContentPanel('centerNorth', {title: 'Tests', closable:false}));
                centerLayout.add('center', new Ext.ContentPanel('centerCenter', {title: '', closable:false}));
                centerLayout.add('south', new Ext.ContentPanel('centerSouth', {title: 'Testset Results', closable:false}));
//
                layout = new Ext.BorderLayout(document.body, {
                    hideOnLayout: true,
                    north: {
                        split:false,
                        initialSize: 50,
                        maxSize: 100,
                        collapsible: true,
                        titlebar: false
                    },
                    west: {
                        split:true,
                        initialSize: 400,
                        minSize: 175,
                        maxSize: 400,
                        titlebar: false,
                        collapsible: true
                    },
                    east: {
                        split:true,
                        initialSize: 400,
                        minSize: 175,
                        maxSize: 400,
                        titlebar: false,
                        collapsible: true,
                        tabPosition:'top',
                        autoscroll:true
                    },
                    south: {
                        split:true,
                        initialSize: 200,
                        minSize: 20,
                        maxSize: 400,
                        titlebar: true,
                        collapsible: true
                    },
                    center: {
                        titlebar: false,
                        autoScroll:true,
                        tabPosition:'top'
                    }
                });

                layout.add('north', new Ext.ContentPanel('north', 'North'));
                layout.add('west', new Ext.NestedLayoutPanel(westLayout, {closable: false}));
                layout.add('center', new Ext.NestedLayoutPanel(centerLayout, {closable:false}));
                layout.add('east', new Ext.NestedLayoutPanel(eastLayout, {closable:false}));
                layout.add('south', new Ext.ContentPanel('south', {title: "Edit", closable: false}));
                layout.getRegion('center').showPanel('center');
            }
        }

    }();
    Ext.EventManager.onDocumentReady(TestFireMain.init, TestFireMain, true);
</script>
</head>
<body class="ytheme-gray">
<f:view>
    <div id="container">

        <div id="westNorth" class="ylayout-inactive-content">
            <div id="testset-grid" style="border: 1px solid #cccccc; overflow: hidden;">
            </div>
        </div>

        <div id="westCenter" class="ylayout-inactive-content">
        </div>


        <div id="westSouth" class="ylayout-inactive-content">
            <div id="agent-grid" style="border: 1px solid #cccccc; overflow: hidden;">
            </div>
        </div>

        <div id="west" class="ylayout-inactive-content">

        </div>
        <div id="north" class="ylayout-inactive-content">
            <div id="masthead">
                <h1 id="siteName">TestFire</h1>
                <c:if test="${pageContext.request.userPrincipal.name != null}">
                    <span style="float:right ">Logged In: ${pageContext.request.userPrincipal.name}</span>
                </c:if>
                <div id="globalNav">
                    <h:form>
                        <a id="href_home" href="/home.jsf">Home</a> |
                        <c:choose>
                            <c:when test="${pageContext.request.userPrincipal.name != null}">
                                <h:commandLink id="logout" action="nav_logout" actionListener="#{UserBean.userLogout}">
                                    <h:outputText value="Log Out |"/>
                                </h:commandLink>
                            </c:when>
                            <c:otherwise>
                                <a id="href_account" href="/user/account.jsf">Log In</a> |
                            </c:otherwise>
                        </c:choose>
                    </h:form>
                </div>
            </div>
        </div>

        <div id="eastNorth" class="ylayout-inactive-content">
            <div id="queue-summary-grid" style="border: 1px solid #cccccc; overflow: hidden;">
            </div>
        </div>

        <div id="eastCenter" class="ylayout-inactive-content">
            <div id="queuetestsets-grid" style="border: 1px solid #cccccc; overflow: hidden;">

            </div>

        </div>

        <div id="eastSouth" class="ylayout-inactive-content">
            <div id="inUseAgent-grid" style="border: 1px solid #cccccc; overflow: hidden;">

            </div>
        </div>


        <div id="east" class="yarrr ylayout-inactive-content">

        </div>

        <div id="center" class="ylayout-active-content">


        </div>

        <div id="centerNorth" class="ylayout-active-content">
            <div id="test-grid" style="height:400; width: 800;border: 1px solid #cccccc; overflow: hidden;">

            </div>
        </div>
        <div id="centerCenter" class="ylayout-active-content">

        </div>

        <div id="centerSouth" class="ylayout-active-content">
            <div id="testsetResult-grid" style="height:400; width: 1000;border: 1px solid #cccccc; overflow: hidden;">

            </div>
        </div>

        <div id="south" class="ylayout-inactive-content">
            <div id="queue-editor-grid" style="border: 1px solid #cccccc; overflow: hidden;">
            </div>
            <div id="testset-info-grid" style="border: 1px solid #cccccc; overflow: hidden;">
            </div>
            <div id="agent-info-grid" style="border: 1px solid #cccccc; overflow: hidden;">
            </div>
        </div>
    </div>
</f:view>
</body>
</html>
